<template>
  <div>
    <basic-container>
      <div class="header">
        <!--日期与模板-->
        <div class="header-up">
          <div class="date-template">
            <div class="dt-item">
              <el-date-picker
                size="mini"
                v-model="queryDate"
                type="daterange"
                align="right"
                unlink-panels
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                :clearable="false"
                @change="getData">
              </el-date-picker>
            </div>
            <div class="dt-item">
              <el-button size="mini" @click="kpiDrawer = true">kpi指标</el-button>
            </div>
            <div class="dt-item">
              <el-select v-model="orderTargetValue" placeholder="请选择" style="width: 180px;"
                         size="mini" @change="getData"
              >
                <el-option
                  v-for="item in orderTargetList"
                  :key="item.value"
                  :label="'排序指标：'+item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="dt-item">
              <el-button size="mini" :disabled="goodTopCreativeList.length === 0" @click="addFeedbackByGood">以最高生成素材反馈
              </el-button>
            </div>
            <div class="dt-item">
              <el-button size="mini" :disabled="goodTopCreativeList.length === 0" @click="addFeedbackByBad">以最低生成素材反馈
              </el-button>
            </div>
          </div>
        </div>
        <!--筛选条件-->
        <cs-filter-query ref="csFilterQueryRef" :options="filterQueryOptions"
                         @change="handleChangeFilter"></cs-filter-query>
      </div>
    </basic-container>
    <el-row>
      <el-col :span="12">
        <top-creative v-loading="goodIsLoading" title="最高" :creative-list="intactGoodCreativeList"
                      :current="goodPage"
                      :total="goodTotal"
                      @change-page="changeGoodPage"
                      @click-creative="onCreativeTagsClick"></top-creative>
      </el-col>
      <el-col :span="12">
        <top-creative v-loading="badIsLoading" title="最低" :creative-list="intactBadCreativeList"
                      :current="badPage"
                      :total="badTotal"
                      @change-page="changeBadPage"
                      @click-creative="onCreativeTagsClick"></top-creative>
      </el-col>
    </el-row>
    <basic-container>
      <div slot="header" class="detail-header">
        <div class="detail-header-left">
          <cs-card-title>素材排行</cs-card-title>
          <el-radio-group v-model="chartRankingVal" size="mini" @change="getCreativeRanking">
            <el-radio-button label="最高"></el-radio-button>
            <el-radio-button label="最低"></el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <creative-ranking-chart ref="CreativeRankingChart" :chart-data="chartData"></creative-ranking-chart>
    </basic-container>
    <el-dialog
      :visible="creativeInfoDialog.dialogVisible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :append-to-body="true"
      style="text-align: center"
      :before-close="
        () => {
        creativeInfoDialog.dialogVisible = false;
        }
      "
    >
      <creative-info v-if="creativeInfoDialog.dialogVisible"
                     :creative-id="creativeInfoDialog.creativeId"></creative-info>
    </el-dialog>
    <el-drawer
      title="KPI指标"
      size="800px"
      :visible.sync="kpiDrawer"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :wrapperClosable="false"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <div class="kpi-box">
          <el-form ref="kpiForm" label-position="top" :model="kpiForm" label-width="80px">
            <el-form-item label="KPI">
              <el-radio-group v-model="kpiForm.target">
                <el-radio :label="item" v-for="item in kpiTargetList" :key="item">{{ item }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-table
                :data="kpiForm.filterItems"
                style="width: 100%"
              >
                <el-table-column
                  prop="platform"
                  label="媒体">
                  <template v-slot="{row}">
                    <el-select size="mini" v-model="row.platform" placeholder="请选择">
                      <el-option
                        v-for="item in platformList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="os"
                  label="操作系统">
                  <template v-slot="{row}">
                    <el-select size="mini" v-model="row.os" placeholder="请选择">
                      <el-option
                        v-for="item in oslist"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="country"
                  label="投放地区">
                  <template v-slot="{row}">
                    <el-select filterable clearable size="mini" v-model="row.country" placeholder="请选择">
                      <el-option
                        v-for="item in nationList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="standard"
                  label="达标"
                  width="200">
                  <template v-slot="{row}">
                    <el-select style="width: 100px" size="mini" v-model="row.standard.condition">
                      <el-option
                        v-for="item in compareList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <el-input style="width: 180px" type="number" size="mini" v-model="row.standard.value"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="exceed"
                  label="超标"
                  width="200">
                  <template v-slot="{row}">
                    <el-select style="width: 100px" size="mini" v-model="row.exceed.condition">
                      <el-option
                        v-for="item in compareList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <el-input type="number" size="mini" v-model="row.exceed.value"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  width="50">
                  <template v-slot="{row, column, $index}">
                    <i class="el-icon-delete" style="cursor: pointer" @click="removeFilterItems($index)"></i>
                  </template>
                </el-table-column>
              </el-table>
              <el-link type="primary" @click="addFilterItems">+ 添加指标</el-link>
            </el-form-item>
          </el-form>
        </div>
        <template v-slot:bottom>
          <el-button size="mini" type="primary" @click="submitKpiTarget">保存</el-button>
          <el-button size="mini" @click="kpiDrawer = false">取消</el-button>
        </template>
      </cs-drawer-container>
    </el-drawer>
  </div>
</template>

<script>
import CsFilterQuery from "@/components/CsFilterQuery/CsFilterQuery";
import KpiConfig from "@/views/creativeReport/components/KpiConfig";
import TopCreative from "@/views/creativeReport/creative-board/components/TopCreative";
import {createEventHandler} from "@/util/events";
import {getCreativePerformanceRanking, getDesignerList, getList2} from "@/api/offer/creativeperformance";
import {getSysDictList} from "@/api/system/dict";
import CsCardTitle from "@/components/CsCardTitle/CsCardTitle";
import Moment from "moment";
import CreativeRankingChart from "@/views/creativeReport/creative-board/components/CreativeRankingChart";
import creativeInfo from "@/views/creativeReport/components/creativeInfo";
import {getAllUser} from "@/api/user";
import {getKpiConfig, submitKpiConfig} from "@/api/offer/creativeperformance";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import _ from 'lodash'
import {mapState} from "vuex";

export default {
  name: "CreativeBoard",
  components: {
    CsFilterQuery,
    KpiConfig,
    TopCreative,
    CsCardTitle,
    CreativeRankingChart,
    creativeInfo,
    CsDrawerContainer
  },
  data() {
    const that = this
    const start = new Date()
    const end = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    end.setTime(end.getTime() - 3600 * 1000 * 24)
    return {
      kpiDrawer: false,
      pickerOptions: {
        onPick({minDate, maxDate}) {
          if (minDate) {
            that.pickerMinDate = minDate.getTime()
          }
          if (maxDate) {
            that.pickerMinDate = 0
          }
        },
        disabledDate(time) {
          if (that.pickerMinDate !== 0) {
            return (
              that.pickerMinDate - 3600 * 1000 * 24 * 30 > time.getTime() ||
              that.pickerMinDate + 3600 * 1000 * 24 * 30 < time.getTime() ||
              time.getTime() > Date.now()
            )
          } else {
            return time.getTime() > Date.now();
          }
        }
      },
      queryDate: [Moment(start).format('YYYY-MM-DD'), Moment(end).format('YYYY-MM-DD')],
      // offerId: this.$store.state.user.offer,
      eventHandler: null,
      orderTargetValue: 'allExpend',
      orderTargetList: [
        {
          label: '花费',
          value: 'allExpend'
        },
        {
          label: '点击',
          value: 'clicks'
        },
        {
          label: '曝光',
          value: 'impressions'
        }, {
          label: 'CTR',
          value: 'ctr'
        }, {
          label: 'CVR',
          value: 'cvr'
        }, {
          label: '安装',
          value: 'install'
        }, {
          label: '安装成本',
          value: 'installCost'
        }
      ],
      // kpi指标
      orderKpiTarget: undefined,
      goodPage: 1,
      goodTotal: 0,
      badPage: 1,
      badTotal: 0,
      // 最好前10
      goodTopCreativeList: [],
      // 最差前10
      badTopCreativeList: [],
      filterQueryObj: {},
      // 设计师
      designerList: [],
      // 国家列表
      nationList: [],
      // 平台列表
      platformList: [],
      // 操作系统
      oslist: [
        {
          label: 'Android',
          value: '1'
        }, {
          label: 'IOS',
          value: '2'
        }, {
          label: 'Website',
          value: '3'
        }
      ],
      goodIsLoading: false,
      badIsLoading: false,
      chartRankingVal: '最高',
      // 排行ids字符串
      goodRankingIds: '',
      badRankingIds: '',
      // 表格数据
      chartData: [],
      // 完整数据
      intactGoodCreativeList: [],
      intactBadCreativeList: [],
      creativeInfoDialog: {
        dialogVisible: false,
        name: '',
        creativeId: '',
      },
      // 所有用户
      allUserList: [],
      kpiForm: {
        target: '',
        filterItems: []
      },
      // kpi指标
      kpiTargetList: ['花费', '曝光', '点击', 'CTR', '安装', 'CVR', '安装成本'],
      // 对比指标
      compareList: [
        {
          label: '>=',
          value: '>='
        }, {
          label: '>',
          value: '>'
        }, {
          label: '<',
          value: '<'
        }, {
          label: '<=',
          value: '<='
        }
      ]
    }
  },
  computed: {
    ...mapState({
      offerId: state => state.user.offer
    }),
    // 筛选组件配置
    filterQueryOptions() {
      return [
        {
          value: 'shortId',
          label: '短ID',
        },
        {
          value: 'name',
          label: '素材名',
        },
        {
          value: 'localFilename',
          label: '本地文件名',
        },
        {
          value: 'type',
          label: '素材类型',
          children: [
            {
              value: '0',
              label: '图片',
            },
            {
              value: '1',
              label: '视频',
            }
          ]
        },
        {
          value: 'designer',
          label: '设计师',
          queryList: this.allUserList
        }, {
          value: 'operator',
          label: '优化师',
          queryList: this.allUserList
        }, {
          value: 'platform',
          label: '投放媒体',
          children: this.platformList
        }, {
          value: 'country',
          label: '投放地区',
          queryList: this.nationList
        },
        {
          value: 'os',
          label: '操作系统',
          children: this.oslist
        },
        {
          value: 'requestId',
          label: '需求ID'
        }, {
          value: 'requestName',
          label: '需求名称'
        }]
    },
  },
  async created() {
    getAllUser({statusList: '0,1,2', isAll: true}).then(res => {
      this.allUserList = res.data.data.map(item => {
        return {
          label: item.realName,
          value: item.id
        }
      })
    });
    this.getDesignerList()
    this.getSysDictList()
    // this.eventHandler = createEventHandler("offerCenter")
    //   .addListener(async event => {
    //     if (event.message === 'offerChanged' && event.offerId && event.offerId !== "") {
    //       await this.getKpiConfig()
    //       this.offerId = event.offerId
    //       this.orderTargetValue = this.getTarget(this.kpiForm.target)
    //       await this.getData()
    //     }
    //   });
    await this.getKpiConfig()
    this.orderTargetValue = this.getTarget(this.kpiForm.target)
    await this.getData()

    // console.log(this.eventHandler)
  },
  watch: {
    // chartRankingVal: {
    //   handler: function (val) {
    //     console.log(val)
    //     if (val === '最高') {
    //       this.rankingIds = this.goodTopCreativeList.length > 0 ? this.goodTopCreativeList.map(item => item.creativeId).join(',') : ''
    //     } else {
    //       this.rankingIds = this.badTopCreativeList.length > 0 ? this.badTopCreativeList.map(item => item.creativeId).join(',') : ''
    //     }
    //   },
    //   immediate: true
    // }
    offerId: {
      handler:async function () {
        await this.getKpiConfig()
        this.orderTargetValue = this.getTarget(this.kpiForm.target)
        await this.getData()
        await this.getCreativeRanking()
      }
    }
  },
  methods: {
    // 初始化数据
    async getData() {
      this.goodPage = 1
      this.badPage = 1
      await Promise.all([this.getGoodTopCreativeList(), this.getBadTopCreativeList()])
      await this.getCreativeRanking()
    },
    // 筛选查询
    handleChangeFilter(val) {
      this.filterQueryObj = val
      this.getData()
    },
    // 获取最好的10条记录
    async getGoodTopCreativeList() {
      const target = this.orderTargetValue
      this.goodIsLoading = true
      const params = {
        current: this.goodPage,
        size: 10,
        sortList: JSON.stringify([{name: target, orderBy: 'desc'}]),
      }
      const data = {
        offerId: this.offerId,
        beginDate: this.queryDate ? this.queryDate[0] : null,
        endDate: this.queryDate ? this.queryDate[1] : null,
        ...this.filterQueryObj
      }
      const {data: res} = await getList2(params, data).finally(() => {
        this.goodIsLoading = false
      })
      this.intactGoodCreativeList = res.data.records
      this.goodTotal = res.data.total
      this.goodTopCreativeList = res.data.records.map(item => {
        // 改花费字段
        return {
          spend: item.allExpend,
          creativeUrl: item.creativeUrl,
          creativeName: item.performanceName,
          creativeId: item.id,
          impressions: item.impressions,
          clicks: item.clicks,
          ctr: item.ctr,
          install: item.install,
          cvr: item.cvr,
          shortId: item.shortId,
          type: item.type
        }
      })
      this.goodRankingIds = this.goodTopCreativeList.length > 0 ? this.goodTopCreativeList.map(item => item.creativeId).join(',') : ''
    },
    // 获取最差的10条记录
    async getBadTopCreativeList() {
      const target = this.orderTargetValue
      this.badIsLoading = true
      const params = {
        current: this.badPage,
        size: 10,
        sortList: JSON.stringify([{name: target, orderBy: 'asc'}]),
      }
      const data = {
        offerId: this.offerId,
        beginDate: this.queryDate ? this.queryDate[0] : null,
        endDate: this.queryDate ? this.queryDate[1] : null,
        ...this.filterQueryObj
      }
      const {data: res} = await getList2(params, data).finally(() => {
        this.badIsLoading = false
      })
      this.intactBadCreativeList = res.data.records
      this.badTotal = res.data.total
      this.badTopCreativeList = res.data.records.map(item => {
        // 改花费字段
        return {
          spend: item.allExpend,
          creativeUrl: item.creativeUrl,
          creativeName: item.performanceName,
          creativeId: item.id,
          impressions: item.impressions,
          clicks: item.clicks,
          ctr: item.ctr,
          install: item.install,
          cvr: item.cvr,
          shortId: item.shortId,
          type: item.type
        }
      })
      this.badRankingIds = this.badTopCreativeList.length > 0 ? this.badTopCreativeList.map(item => item.creativeId).join(',') : ''
    },
    // 翻页
    changeGoodPage(val) {
      if (val === 'forward') {
        if (this.goodPage * 10 >= this.goodTotal) return
        this.goodPage++
      } else {
        if (this.goodPage === 1) return
        this.goodPage--
      }
      this.getGoodTopCreativeList()
    },
    // 翻页
    changeBadPage(val) {
      if (val === 'forward') {
        if (this.badPage * 10 >= this.badTotal) return
        this.badPage++
      } else {
        if (this.badPage === 1) return
        this.badPage > 1 ? this.badPage-- : 1
      }
      this.getBadTopCreativeList()
    },
    // 获取设计师
    async getDesignerList() {
      const res = await getDesignerList(this.offer)
      this.designerList = res.data.data.map(item => {
        return {
          label: item.realName,
          value: item.id
        }
      })
    },
    // 获取字典中列表
    async getSysDictList() {
      const {platforms, nation} = await getSysDictList("platforms,nation")
      this.platformList = platforms.map(item => {
        return {
          label: item.dictValue,
          value: item.dictKey
        }
      })
      this.nationList = nation.map(item => {
        return {
          label: item.dictValue,
          value: item.dictKey
        }
      })
    },
    // 生成素材反馈
    addFeedbackByGood() {
      this.$router.push({
        path: '/creativeReport/creative-feedback/index',
        // query: {
        //   add: true,
        //   data: this.goodTopCreativeList,
        //   startDate: this.queryDate ? this.queryDate[0] : null,
        //   endDate: this.queryDate ? this.queryDate[1] : null
        // }
      })
      // 总线发送到目标数据有可能不成功设置延迟
      setTimeout(() => {
        this.$bus.emit('addCreativeReport', {
          add: true,
          data: this.goodTopCreativeList,
          startDate: this.queryDate ? this.queryDate[0] : null,
          endDate: this.queryDate ? this.queryDate[1] : null
        })
      }, 500)
      // this.$nextTick(() => {
      //   this.$bus.emit('addCreativeReport', {
      //     add: true,
      //     data: this.goodTopCreativeList,
      //     startDate: this.queryDate ? this.queryDate[0] : null,
      //     endDate: this.queryDate ? this.queryDate[1] : null
      //   })
      // })

    },
    addFeedbackByBad() {
      this.$router.push({
        path: '/creativeReport/creative-feedback/index',
        // query: {
        //   add: true,
        //   data: this.badTopCreativeList,
        //   startDate: this.queryDate ? this.queryDate[0] : null,
        //   endDate: this.queryDate ? this.queryDate[1] : null
        // }
      })
      setTimeout(() => {
        this.$bus.emit('addCreativeReport', {
          add: true,
          data: this.badTopCreativeList,
          startDate: this.queryDate ? this.queryDate[0] : null,
          endDate: this.queryDate ? this.queryDate[1] : null
        })
      }, 500)
      // this.$nextTick(() => {
      //   this.$bus.emit('addCreativeReport', {
      //     add: true,
      //     data: this.badTopCreativeList,
      //     startDate: this.queryDate ? this.queryDate[0] : null,
      //     endDate: this.queryDate ? this.queryDate[1] : null
      //   })
      // })
    },
    async getCreativeRanking() {
      let rankingIds = ''
      if (this.chartRankingVal === '最高') {
        rankingIds = this.goodRankingIds
      } else {
        rankingIds = this.badRankingIds
      }
      const {data: res} = await getCreativePerformanceRanking({
        creativeIds: rankingIds,
        sortName: this.orderTargetValue,
        beginDate: this.queryDate ? this.queryDate[0] : null,
        endDate: this.queryDate ? this.queryDate[1] : null
      })
      this.chartData = res.data
      this.chartData.yAxis = this.chartData.yAxis.map(item => {
        if (this.chartRankingVal === '最高') {
          item.shortId = this.intactGoodCreativeList.find(top => top.creativeId === item.creativeId).shortId
        } else {
          item.shortId = this.intactBadCreativeList.find(top => top.creativeId === item.creativeId).shortId
        }
        return item
      })
      this.$nextTick(() => {
        console.log('表格')
        this.$refs.CreativeRankingChart.initChart()
      })
    },
    // 详情
    onCreativeTagsClick(row) {
      this.$nextTick(() => {
        this.creativeInfoDialog.name = row.performanceName;
        this.creativeInfoDialog.creativeId = row.id;
        this.creativeInfoDialog.dialogVisible = true;
      });
    },
    // // getTarget
    // getTarget(val) {
    //   this.orderKpiTarget = val
    // },
    // // kpi改变指标
    // async changeKpi(val) {
    //   this.orderKpiTarget = val
    //   this.goodPage = 1
    //   this.badPage = 1
    //   await Promise.all([this.getGoodTopCreativeList(), this.getBadTopCreativeList()])
    //   await this.getCreativeRanking()
    // },
    // 添加指标
    addFilterItems() {
      this.kpiForm.filterItems.push(
        {
          platform: '',
          os: '',
          country: '',
          standard: {
            condition: '',
            value: ''
          },
          exceed: {
            condition: '',
            value: ''
          }
        }
      )
    },
    // 移除指标
    removeFilterItems(index) {
      this.kpiForm.filterItems.splice(index, 1)
    },
    // 提交kpi指标
    async submitKpiTarget() {
      // if (this.kpiForm.filterItems.length === 0) return this.$message.warning('请完善指标')
      const obj = this.kpiForm.filterItems.find(item => {
        return item.platform === '' || item.os === '' || item.country === '' || item.standard.condition === '' || item.standard.value === ''
      })
      if (obj !== undefined) return this.$message.warning('请完善指标')
      // 后端框架接收null会转义此代码作为调整
      const temp = _.cloneDeep(this.kpiForm)
      temp.offerId = this.offerId
      temp.filterItems = temp.filterItems.map(item => {
        if (item.exceed.condition === '' || item.exceed.value === '' || JSON.stringify(item.exceed.condition) === '{}' || item.exceed.value === -1) {
          item.exceed = null
        }
        return item
      })
      // this.$emit('update:visible', false)
      const {data: res} = await submitKpiConfig(temp)
      if (res.code !== 200) return
      this.$message.success('保存成功')
      this.kpiDrawer = false
    },
    // 获取kpi数据
    async getKpiConfig() {
      const {data: res} = await getKpiConfig({offerId: this.offerId})
      if (res.data.id === undefined) return
      this.kpiForm.id = res.data.id
      this.kpiForm.target = res.data.target
      this.kpiForm.filterItems = res.data.filterItems
    },
    // 返回指标
    getTarget(target) {
      return target==='' ? 'allExpend' : this.orderTargetList.find(item => item.label === target).value
    }
  }
}
</script>

<style lang="scss" scoped>
.header {

  .header-up {
    display: flex;
    justify-content: space-between;

    .date-template {
      .dt-item {
        display: inline-block;
        margin-bottom: 10px;
        margin-right: 10px;
      }
    }
  }
}

.detail-header {
  .detail-header-left {
    display: flex;
    align-items: center;

    .el-radio-group {
      margin-left: 20px;
    }
  }
}

.kpi-box {
  padding: 0 15px;

  .el-table {
    ::v-deep .cell {
      display: flex;
    }
  }
}
</style>
